<template>
  <div>
    <div id="viewDiv">
      <div id='select-by-polygon'
           class="esri-widget esri-widget--button esri-widget esri-interactive"
           title="Select features by polygon"></div>
    </div>

  </div>
</template>
 
<script>
// 控制子图层显示隐藏
import esriLoader from "esri-loader"
import Bus from "../utils/bus.js"
export default {
  name: "",
  components: { Bus },
  props: {},
  data () {
    return {}
  },
  created () { },

  mounted () {
    const options = {
      url:
        "http://172.16.0.25/arcgis_js_v412_api/arcgis_js_api/library/4.12/init.js"
    }
    esriLoader
      .loadModules(
        [
          "esri/Map",
          "esri/views/MapView",
          "esri/layers/WebTileLayer",
          "esri/layers/FeatureLayer",
          "esri/layers/MapImageLayer",
          "esri/widgets/Home",
          "esri/widgets/Widget",
          "esri/widgets/Zoom",
          "esri/renderers/HeatmapRenderer",
          "esri/widgets/Feature",
          "esri/views/draw/Draw",
          "esri/Graphic",
          "esri/geometry/geometryEngine",
          // 地图分析模块
          "esri/layers/GraphicsLayer",
          "esri/widgets/Sketch/SketchViewModel",
          "esri/tasks/Geoprocessor",
          "esri/tasks/support/FeatureSet",
          "esri/widgets/Sketch"
        ],
        options
      )
      .then(
        ([
          Map,
          MapView,
          WebTileLayer,
          FeatureLayer,
          MapImageLayer,
          Home,
          Widget,
          Zoom,
          HeatmapRenderer,
          Feature, Draw, Graphic, geometryEngine,
          SketchViewModel,
          Geoprocessor,
          FeatureSet,
          GraphicsLayer,
          Sketch

        ]) => {
          // 周浩提供的地图服务
          var layerTiles = new WebTileLayer({
            urlTemplate: "http://106.15.228.37:8090/{level}/{col}/{row}.png"
          })

          var polygonGraphicsLayer;
          var sketchViewModel;

          var drawGraphic;
          var inputGraphicContainer = [];
          var featureSet = new FeatureSet();
          // arcgis官方地图
          // var layer1 = new FeatureLayer({
          //   // autocasts as new PortalItem()
          //   portalItem: {
          //     id: "234d2e3f6f554e0e84757662469c26d3"
          //   },
          //   outFields: ["*"]
          // })
          // var layer2 = new FeatureLayer({
          //   url: 'http://172.16.0.224:6080/arcgis/rest/services/DXKJ/DXKJ/MapServer'
          // })

          // 实验图层显示隐藏功能
          var layer3 = new MapImageLayer({
            url:
              "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer",
            sublayers: [
              {
                id: 3,
                visible: false
              },
              {
                id: 2,
                visible: true
              },
              {
                id: 1,
                visible: true
              },
              {
                id: 0,
                visible: true
              }
            ]
          })

          var layer4 = new FeatureLayer({
            url: 'http://172.16.0.224:6080/arcgis/rest/services/DXKJ/GHPQ/MapServer/0'
          })
          var layer5 = new FeatureLayer({
            url: 'http://172.16.0.224:6080/arcgis/rest/services/DXKJ/GHPQ/MapServer/1'
          })
          //构造gp服务cjyiz
          var gpUrl = "http://172.16.0.224:6080/arcgis/rest/services/DXKJ/getArea/GPServer/getArea"; //GP服务
          var gp = new Geoprocessor(gpUrl);
          var layerGHPQ = new FeatureLayer({
            url: "http://172.16.0.224:6080/arcgis/rest/services/DXKJ/GHPQ/MapServer/1"
          });
          var fillSymbol = {
            type: "simple-fill", // autocasts as new SimpleFillSymbol()
            color: [226, 119, 40, 0.75],
            outline: {
              color: [255, 255, 255],
              width: 1
            }
          };
          //将图层加入到地图上
          var map = new Map({
            basemap: "osm",
            layers: [layerTiles, layer4, layer5, layerGHPQ],
            slider: false
          })
          const mapCenter = [118.779038, 32.04841]
          const view = new MapView({
            container: "viewDiv",
            map: map,
            zoom: 13,
            center: mapCenter,
            // 高亮颜色渲染
            highlightOptions: {
              color: '#00d5fc'
            }
          })
          // 根据图形查询图层
          //  function queryFeatureLayer (geometry) {
          //                 console.log(geometry)
          //                 console.log('查询参数')
          //                 let query = layerFW.createQuery()
          //                 query.geometry = geometry
          //                 console.log(layerFW)
          //                 console.log(query)
          //                 layerFW.queryFeatures(query).then(function (res) {
          //                   console.log(res)
          //                   addGraphics(res, true);
          //                 });
          //               }
          // 加载热力图JSON数据,封装好的函数，在map对象后面调用，因为其中调用了map对象
          var heatMap = function () {
            var heatmapRenderer = new HeatmapRenderer({
              //设置渲染器
              colorStops: [
                { color: "rgba(63, 40, 102, 0)", ratio: 0 },
                { color: "#472b77", ratio: 0.083 },
                { color: "#4e2d87", ratio: 0.166 },
                { color: "#563098", ratio: 0.249 },
                { color: "#5d32a8", ratio: 0.332 },
                { color: "#6735be", ratio: 0.415 },
                { color: "#7139d4", ratio: 0.498 },
                { color: "#7b3ce9", ratio: 0.581 },
                { color: "#853fff", ratio: 0.664 },
                { color: "#a46fbf", ratio: 0.747 },
                { color: "#c29f80", ratio: 0.83 },
                { color: "#e0cf40", ratio: 0.913 },
                { color: "#ffff00", ratio: 1 }
              ],
              maxPixelIntensity: 10,
              minPixelIntensity: 0
            })
            // 读取json数据
            const heatDataUrl = "http://172.16.0.25/heatMap.json"
            $.getJSON(heatDataUrl, {}, function (data, textStatus, jqXHR) {
              var features = []
              for (var i = 0; i < data.heatData.length; i++) {
                var x = data.heatData[i].lng
                var y = data.heatData[i].lat
                features.push({
                  geometry: {
                    type: "point",
                    x: x,
                    y: y
                  },
                  attributes: {
                    ObjectID: i //重要！！！
                  }
                })
              }

              var featureLayer = new FeatureLayer({
                source: features, //点数据集
                title: "热力图",
                objectIdField: "ObjectID", //重要！！！
                renderer: heatmapRenderer //渲染器
              })
              map.add(featureLayer)
            })
          }
          heatMap()

          // 地图区域高亮及点击高亮区域触发弹框
          var selectSpace = function (featureLayer) {
            view.whenLayerView(featureLayer).then(function (layerView) {
              let highlight;
              // 监听点击事件,为什么事件会触发那么多次
              view.on('immediate-click', (event) => {
                view.hitTest(event).then((event) => {
                  let results = event.results
                  let result = results[0];
                  console.log('图层' + result.graphic.sourceLayer.layerId)
                  console.log('索引' + result.graphic.attributes.FID)
                  if (result) {
                    Bus.$emit('showUnderground', result)
                  }
                })
              })
              // 监听鼠标移动事件
              view.on("pointer-move", function (event) {
                //返回当前鼠标所在区域图层中最顶层的要素
                view.hitTest(event).then(function (event) {
                  let results = event.results
                  let result = results[0];
                  let featureLayerId = result.graphic.sourceLayer.layerId
                  highlight && highlight.remove();

                  // 由于不做图层id判断的话，不同图层要素可能会互相影响，有相同FID的不同result.graphic会互相影响
                  if (result && featureLayerId === featureLayer.layerId) {
                    highlight = layerView.highlight(result.graphic)
                  }
                });
              })
            })
          }
          view.when().then(function () {
            selectSpace(layer4)
            selectSpace(layer5)
          })

          // 地图工具编辑

          // 地图上回到初始中心开始
          Bus.$on("mapHome", e => {
            view.goTo({
              center: mapCenter,
              zoom: 13
            })
          })
          // 地图上回到初始中心结束
          // 移除地图缩放工具
          view.ui.remove("zoom")
          // 显示隐藏地图控件
          Bus.$on("mapToggle", e => {
            layer3.sublayers.items[1].visible = !layer3.sublayers.items[1]
              .visible
          })
          // cjyiz123
          const citiesSym = {
            type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
            size: 5,
            color: [255, 0, 0],
            outline: null
          };

          const citiesRenderer = {
            type: "simple", // autocasts as new SimpleRenderer()
            symbol: citiesSym
          };
          var fillSymbol = {
            type: "simple-fill", // autocasts as new SimpleFillSymbol()
            color: [226, 119, 40, 0.75],
            outline: {
              color: [255, 255, 255],
              width: 1
            }
          };
          setUpSketchViewModel();

          function setUpSketchViewModel () {
            polygonGraphicsLayer = new GraphicsLayer();
            map.add(polygonGraphicsLayer);
            view.ui.add("select-by-polygon", "top-left");
            const selectButton = document.getElementById("select-by-polygon");
            // click event for the button
            selectButton.addEventListener("click", function () {
              view.popup.close();
              // polygonGraphicsLayer.remove(drawGraphic);
              // ready to draw a polygon
              sketchViewModel.create("polygon");
            });

            // create a new sketch view model set its layer
            sketchViewModel = new SketchViewModel({
              view: view,
              layer: polygonGraphicsLayer,
              pointSymbol: {
                type: "simple-marker",
                color: [255, 255, 255, 0],
                size: "1px",
                outline: {
                  color: "gray",
                  width: 0
                }
              }
            });
          }


          sketchViewModel.on("create", function (event) {
            if (event.state === "complete") {
              // this polygon will be used to query features that intersect it
              drawGraphic = event.graphic; //每次绘制完以后的graphic
              console.log(drawGraphic)
              inputGraphicContainer.push(drawGraphic);
              featureSet.features = inputGraphicContainer;
              // 入口图层
              var params = {
                pclip: featureSet
              }
              // console.log(params)
              // gp.execute(params).then(drawResultData);//同步
              console.log(gp)
              gp.submitJob(params).then(drawResultData); //异步
            }
          });

          function drawResultData (result) {
            var jobId = result.jobId;
            var status = result.jobStatus;
            if (status == 'job-succeeded') {
              //成功之后，将其中的结果取出来，当然这也是参数名字。
              //在模型中，想要取出中间结果，需要设置为模型参数
              gp.getResultData(jobId, "presult").then(addResults);
            }
          }

          function addResults (results) {

            var resultFeatures = results.value.features;
            var viewshedGraphics = resultFeatures.map(function (feature) {
              feature.symbol = fillSymbol;
              return feature;
            });
            polygonGraphicsLayer.addMany(viewshedGraphics);
          }


          // 画图开始
          // let graphic
          // const draw = new Draw({
          //   view: view
          // });
          // // 绘图按钮
          // document.getElementById("line-button").onclick = function () {
          //   view.graphics.removeAll();
          //   // 创建绘图实例
          //   const action = draw.create("polyline");
          //   // 视图聚焦绘图
          //   view.focus();
          //   // 监听绘图事件，并在地图上画出线条
          //   action.on(
          //     [
          //       "vertex-add",
          //       "vertex-remove",
          //       "cursor-update",
          //       "redo",
          //       "undo",
          //       "draw-complete"
          //     ],
          //     updateVertices
          //   );
          //   action.on("draw-complete", cjyiz)

          // };
          // function cjyiz (event) {
          //   // 获取最后画出的图形
          //   const drawGraphic = createGraphic(event).graphic
          //   console.log(drawGraphic)

          //   inputGraphicContainer.push(drawGraphic)
          //   featureSet.features = inputGraphicContainer
          //   var params = {
          //     pclip: featureSet
          //   }
          //   // console.log(params)
          //   console.log(gp)
          //   gp.submitJob(params).then(drawResultData)
          //   function drawResultData (result) {
          //     var jobId = result.jobId;
          //     var status = result.jobStatus;
          //     if (status == 'job-succeeded') {
          //       //成功之后，将其中的结果取出来，当然这也是参数名字。
          //       //在模型中，想要取出中间结果，需要设置为模型参数
          //       gp.getResultData(jobId, "presult").then(addResults);
          //     }
          //   }

          //   function addResults (results) {

          //     var resultFeatures = results.value.features;
          //     var viewshedGraphics = resultFeatures.map(function (feature) {
          //       feature.symbol = fillSymbol;
          //       return feature;
          //     });
          //     console.log(viewshedGraphics)
          //     layer4.addMany(viewshedGraphics);
          //   }
          //   // console.log(1234)
          // }
          // // 检查最后一个顶点是否闭合图形
          // function updateVertices (event) {
          //   // 从返回的顶点创建折线
          //   if (event.vertices.length > 1) {
          //     const result = createGraphic(event);
          //     // 如果最后一个顶点使图形闭合，就阻止事件
          //     if (result.selfIntersects) {
          //       event.preventDefault();
          //     }
          //   }
          // }
          // // 创建当前画出的图形对象
          // function createGraphic (event) {
          //   const vertices = event.vertices;
          //   view.graphics.removeAll();
          //   //  graphic对象，表示当前画出的图形
          //   graphic = new Graphic({
          //     geometry: {
          //       type: "polyline",
          //       paths: vertices,
          //       spatialReference: view.spatialReference
          //     },
          //     symbol: {
          //       type: "simple-line", // autocasts as new SimpleFillSymbol
          //       color: [99, 90, 141],
          //       width: 4,
          //       cap: "round",
          //       join: "round"
          //     }
          //   });
          //   // 检查折线是否自相交
          //   const intersectingSegment = getIntersectingSegment(graphic.geometry);
          //   // console.log(intersectingSegment)
          //   // 为相交的区域添加一个新的graphic图形
          //   if (intersectingSegment) {
          //     console.log(1)
          //     // featureSet.features = inputGraphicContainer
          //     view.graphics.addMany([graphic, intersectingSegment]);
          //   }
          //   // Just add the graphic representing the polyline if no intersection
          //   else {
          //     // inputGraphicContainer.push(graphic)
          //     // featureSet.features = inputGraphicContainer
          //     view.graphics.add(graphic);
          //   }
          //   // return intersectingSegment
          //   return {
          //     graphic
          //   };
          // }
          // // function that checks if the line intersects itself
          // function isSelfIntersecting (polyline) {
          //   if (polyline.paths[0].length < 3) {
          //     return false;
          //   }
          //   const line = polyline.clone();

          //   //get the last segment from the polyline that is being drawn
          //   const lastSegment = getLastSegment(polyline);
          //   line.removePoint(0, line.paths[0].length - 1);

          //   // returns true if the line intersects itself, false otherwise
          //   return geometryEngine.crosses(lastSegment, line);
          // }
          // //检查线条是否自相交，如果是，改变最后部分的样式告知用户
          // function getIntersectingSegment (polyline) {
          //   if (isSelfIntersecting(polyline)) {
          //     return new Graphic({
          //       geometry: getLastSegment(polyline),
          //       symbol: {
          //         type: "simple-line", // autocasts as new SimpleLineSymbol
          //         style: "short-dot",
          //         width: 3.5,
          //         color: "yellow"
          //       }
          //     });
          //   }
          //   return null;
          // }
          // // 获取最后画出的线段
          // function getLastSegment (polyline) {
          //   const line = polyline.clone();
          //   const lastXYPoint = line.removePoint(0, line.paths[0].length - 1);
          //   const existingLineFinalPoint = line.getPoint(
          //     0,
          //     line.paths[0].length - 1
          //   );
          //   return {
          //     type: "polyline",
          //     spatialReference: view.spatialReference,
          //     hasZ: false,
          //     paths: [
          //       [
          //         [existingLineFinalPoint.x, existingLineFinalPoint.y],
          //         [lastXYPoint.x, lastXYPoint.y]
          //       ]
          //     ]
          //   };
          // }

          // 画图结束


          // 最外层括号
        }
      )
      .catch(err => {
        console.log(err)
      })
  }
} 
</script>
<style>
@import url("http://172.16.0.25/arcgis_js_v412_api/arcgis_js_api/library/4.12/esri/css/main.css");
/* @import "../../static/style/map.scss"; */
/* #select-by-polygon {
  position: fixed;
  height: 30px;
  width: 30px;
  background-color: red;
  left: 500px;
  top: 500px;
} */
</style>